package com.newhis.common;

import com.newhis.common.filter.SqlMonitorSwitch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.*;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Repository;
import org.springframework.util.StopWatch;

import java.util.List;

@Repository
public class DBHelper {

    @Value("${db.slow-sql-millis-seconds:3000}")
    private int slowSqlMillisSeconds;  //默认3000

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private DBSqlHelper dbSqlHelper;

    /**
     * 单个结果查询
     * @param sql
     * @param args
     * @param rowMapper
     * @param <T>
     * @return
     * @throws DataAccessException
     */
    public <T> T queryForObject(String sql, @Nullable Object[] args, RowMapper<T> rowMapper) throws DataAccessException {
        StopWatch sw = new StopWatch();
        sw.start();
        T result = jdbcTemplate.queryForObject(sql, args, rowMapper);
        sw.stop();
        long duration = sw.getTotalTimeMillis();
        if(duration > slowSqlMillisSeconds) {
            dbSqlHelper.recSqlMon(SqlMonitorSwitch.getSqlMonStr(), SqlMonitorSwitch.getSqlMonUrl(), duration);
        }
        return result;
    }

    /**
     * 结果集查询
     * @param sql
     * @param args
     * @param rowMapper
     * @param <T>
     * @return
     * @throws DataAccessException
     */
    public <T> List<T> query(String sql, @Nullable Object[] args, RowMapper<T> rowMapper) throws DataAccessException {
        StopWatch sw = new StopWatch();
        sw.start();
        List<T> list = jdbcTemplate.query(sql, args, rowMapper);
        sw.stop();
        long duration = sw.getTotalTimeMillis();
        if(duration > slowSqlMillisSeconds) {
            dbSqlHelper.recSqlMon(SqlMonitorSwitch.getSqlMonStr(), SqlMonitorSwitch.getSqlMonUrl(), duration);
        }
        return list;
    }

    /**
     * 增删改操作
     * @param sql
     * @param args
     * @return
     */
    public int update(String sql, Object[] args) {
        StopWatch sw = new StopWatch();
        sw.start();
        int i = jdbcTemplate.update(sql, args);
        sw.stop();
        long duration = sw.getTotalTimeMillis();
        if(duration > slowSqlMillisSeconds) {
            dbSqlHelper.recSqlMon(SqlMonitorSwitch.getSqlMonStr(), SqlMonitorSwitch.getSqlMonUrl(), duration);
        }
        return i;
    }

}

